import request from '../../utils/request'
import { formatTime, showSuccess, showError, showLoading, hideLoading } from '../../utils/util'

Page({
    data: {
        currentTab: 'published',
        postList: [],
        page: 1,
        size: 10,
        hasMore: true,
        loading: false,
        refreshing: false
    },

    onLoad() {
        this.loadPosts()
    },

    onPullDownRefresh() {
        this.setData({
            page: 1,
            postList: [],
            hasMore: true,
            refreshing: true
        })
        this.loadPosts().finally(() => {
            this.setData({ refreshing: false })
            wx.stopPullDownRefresh()
        })
    },

    onReachBottom() {
        if (this.data.hasMore && !this.data.loading) {
            this.loadPosts()
        }
    },

    onTabChange(e) {
        const tab = e.currentTarget.dataset.tab
        this.setData({
            currentTab: tab,
            page: 1,
            postList: [],
            hasMore: true
        })
        this.loadPosts()
    },

    async loadPosts() {
        if (this.data.loading) return

        this.setData({ loading: true })

        try {
            let posts = []

            if (this.data.currentTab === 'published') {
                posts = await request.get('/posts/my')
            } else {
                posts = await request.get('/posts/my/likes')
            }

            // 格式化时间
            const formattedPosts = posts.map(post => ({
                ...post,
                createTime: formatTime(post.createTime),
                startTime: formatTime(post.startTime),
                endTime: formatTime(post.endTime)
            }))

            if (posts.length < this.data.size) {
                this.setData({ hasMore: false })
            }

            this.setData({
                postList: [...this.data.postList, ...formattedPosts],
                page: this.data.page + 1
            })
        } catch (error) {
            console.error('加载我的帖子失败:', error)
            showError('加载失败')
        } finally {
            this.setData({ loading: false })
        }
    },

    onPostClick(e) {
        const post = e.currentTarget.dataset.post
        wx.navigateTo({
            url: `/pages/post-detail/post-detail?id=${post.id}`
        })
    },

    onEditPost(e) {
        const post = e.currentTarget.dataset.post
        wx.navigateTo({
            url: `/pages/create-post/create-post?edit=1&id=${post.id}`
        })
    },

    async onDeletePost(e) {
        const post = e.currentTarget.dataset.post

        wx.showModal({
            title: '确认删除',
            content: '确定要删除这个帖子吗？此操作不可撤销。',
            confirmColor: '#ff5252',
            success: async (res) => {
                if (res.confirm) {
                    try {
                        showLoading('删除中...')
                        const result = await request.delete(`/posts/${post.id}`)
                        hideLoading()

                        if (result.success) {
                            showSuccess('删除成功')
                            // 从列表中移除
                            const postList = this.data.postList.filter(p => p.id !== post.id)
                            this.setData({ postList })
                        } else {
                            showError('删除失败')
                        }
                    } catch (error) {
                        hideLoading()
                        showError('删除失败')
                    }
                }
            }
        })
    },

    onCreatePost() {
        wx.navigateTo({
            url: '/pages/create-post/create-post'
        })
    }
})